package cn.layfolk.websocket.listener;

import cn.hutool.json.JSONUtil;
import cn.layfolk.daimao.consts.ErrorCodeEnum;
import cn.layfolk.daimao.consts.MQConstans;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import cn.layfolk.websocket.ws.WebSocketServer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;



@RocketMQMessageListener(
        topic = MQConstans.SECKILL_ORDER_TOPIC,
        consumerGroup = MQConstans.SECKILL_ORDER_FAILED_GROUP,
        selectorExpression = MQConstans.SECKILL_ORDER_FAILED_TAG
)
@Component
public class SeckillOrderFailedMQListener implements RocketMQListener<String> {

    private final Logger log = LoggerFactory.getLogger("SECKILL_ORDER_FAILED_MQ_LISTENER");

    @Override
    public void onMessage(String uuid) {
        log.info("收到订单创建失败结果：{}",uuid);

        // 通知前端下单结果
        Session session = WebSocketServer.clients.get(uuid);
        if (session != null){
            try {
                String json = JSONUtil.toJsonStr(ResponseVo.fail(ErrorCodeEnum.CREATE_ORDER_FAILED));
                session.getBasicRemote().sendText(json);
            } catch (IOException e) {
                log.error("消息发送异常", e);
            }
        }
    }
}
